<?php
/**
 * Created by PhpStorm.
 * Author: QinShuai
 * Email: qinshuai0423@qq.com
 * Date: 2021/7/8
 */

namespace console\controllers;

use yii\console\Controller;
use yii\web\View;

class AutoCreateController extends Controller
{

    public $tableName;

    public $controllerNamespace = "backend\\controllers";
    public $modelNamespace = "backend\\models";


    public function options($actionID)
    {
        return ['tableName'];
    }

    public function optionAliases()
    {
        return ['t' => 'tableName'];
    }

    public function actionIndex($tableName)
    {
        if (!$this->tableName) {
            $this->tableName = trim($tableName);
        }
        $this->createController();
        $this->createModel();
        $this->createView();
    }

    public function parseModelName()
    {
        $name = ucwords(str_replace('_', ' ', $this->tableName));
        return str_replace(' ', '', $name);
    }

    public function parseControllerName()
    {
        return $this->parseModelName() . "Controller";
    }

    public function parseViewPathName()
    {
        return str_replace('_', '-', $this->tableName);
    }

    public function render($template, $params = [])
    {
        $view = new View();
        $params['generator'] = $this;

        return $view->renderFile('./console/template/' . $template, $params, $this);
    }

    public function getTableInfo()
    {

        $db = \Yii::$app->db;
        return $db->getTableSchema($db->tablePrefix . $this->tableName);
    }

    public function writeFile($path, $content)
    {
        $fd = fopen($path, 'w');
        fwrite($fd, $content);
        fclose($fd);
    }

    public function createController()
    {
        $controllerPath = './backend/controllers/' . $this->parseControllerName() . '.php';
        $this->writeFile($controllerPath, $this->render('controller.php'));
    }

    public function createModel()
    {
        $modelPath = './backend/models/' . $this->parseModelName() . '.php';
        $this->writeFile($modelPath, $this->render('model.php'));
    }

    public function createView()
    {
        $viewPath = './backend/views/' . $this->parseViewPathName() . '/';
        if (!is_dir($viewPath)) {
            mkdir($viewPath, 0777);
        }
        $this->writeFile($viewPath . '/index.php', $this->render('view.php'));
    }

}